﻿using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace SalaryChannel.Web
{
    [ServiceContract(Namespace = "http://salary.yangchao.ts.gs.chinamobile/")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class OrderService:ServiceAuthRoot
    {
        [OperationContract]
        public int CreateDeivce(string UserID,string DeviceName,string Remark)
        {
            // 在此处添加操作实现
            try
            {
                Authoricate();
                using (OrderDataClassesDataContext context = new OrderDataClassesDataContext())
                {
                    Order_Device de = new Order_Device
                    {
                        Device_Name = DeviceName,
                        Create_User_ID = UserID,
                        Remark = Remark
                    };
                    context.Order_Device.InsertOnSubmit(de);
                
                    context.SubmitChanges();
                    return 0;
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("ind_order_device_name"))
                {
                    return 1;
                }
                LogManager.Write("OrderService.CreateDeivce:" + ex.Message);
                return -1 ;
            }
        }

        [OperationContract]
        public List<VW_DeviceStock> GetDeviceStock(string Name)
        {
            try
            {
                Authoricate();
                using (OrderDataClassesDataContext context = new OrderDataClassesDataContext())
                {
                    var query = from q in context.VW_DeviceStock                                
                                where string.IsNullOrEmpty(Name) || q.Device_Name.Contains(Name)
                                orderby q.Device_Name
                                select q;
                    if (query.Any())
                    {
                        return query.ToList();
                    }
                    return new List<VW_DeviceStock>();
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("OrderService.GetDeviceStock:" + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public List<VW_DeviceStock> GetOrderStock(string Name)
        {
            try
            {
                Authoricate();
                using (OrderDataClassesDataContext context = new OrderDataClassesDataContext())
                {
                    var query = from q in context.VW_DeviceStock
                                where string.IsNullOrEmpty(Name) || q.Device_Name.Contains(Name)
                                where q.Stock!=0
                                orderby q.Device_Name
                                select q;
                    if (query.Any())
                    {
                        return query.ToList();
                    }
                    return new List<VW_DeviceStock>();
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("OrderService.GetOrderStock:" + ex.Message);
                return null;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="DeviceID"></param>
        /// <param name="UserNum"></param>
        /// <param name="OpUserID"></param>
        /// <param name="Remark"></param>
        /// <returns>0-成功</returns>
        [OperationContract]
        public int OrderDeviceForUser(int DeviceID, string UserNum, string OpUserID, string Remark)
        {
            try
            {
                lock (this)
                {
                    Authoricate();
                    using (OrderDataClassesDataContext context = new OrderDataClassesDataContext())
                    {
                        //var query = from q in context.Order_Stock
                        //            where q.Device_ID == DeviceID
                        //            where q.Stock >= 1
                        //            select q;
                        //if (query.Any())
                        //{
                        //    query.First().Stock--;

                        //    Order_His his = new Order_His
                        //    {
                        //        Device_ID = DeviceID,
                        //        Create_User_ID = OpUserID,
                        //        Order_Time = DateTime.Now,
                        //        Serv_Number = UserNum,
                        //        Is_Cancel = '0',
                        //        Remark = Remark
                        //    };
                        //    context.Order_His.InsertOnSubmit(his);
                        //    context.SubmitChanges();
                        //    return 0;
                        //}
                        return context.SP_Order(DeviceID,UserNum,OpUserID,Remark);
                    } 
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("OrderService.OrderDeviceForUser:" + ex.Message);
                if (ex.Message.ToLower().Contains("ck_stock_biger0"))
                {
                    return 1;
                }
                else if (ex.Message.ToLower().Contains("tri_order_his_num_unique"))
                {
                    return 2;
                }
                return -1;
            }
        }


        [OperationContract]
        public bool AddStock(string UserID, int DeviceID, int AddAmount,string Remark)
        {
            lock (this)
            {
                try
                {
                    Authoricate();
                    using (OrderDataClassesDataContext context = new OrderDataClassesDataContext())
                    {
                        var query = from q in context.Order_Stock
                                    where q.Device_ID == DeviceID
                                    select q;
                        
                        if (query.Any())
                        {
                            query.First().Amount += AddAmount;
                            query.First().Stock += AddAmount;
                        }
                        else
                        {
                            Order_Stock stock = new Order_Stock
                            {
                                Device_ID = DeviceID,
                                Amount = AddAmount,
                                Stock = AddAmount
                            };
                            context.Order_Stock.InsertOnSubmit(stock);
                        }


                        Order_Stock_Mng_His smh = new Order_Stock_Mng_His
                        {
                            Device_ID = DeviceID,
                            User_ID = UserID,
                            Add_Amount = AddAmount,
                            Create_Time = DateTime.Now,
                            Remark = Remark
                        };
                        context.Order_Stock_Mng_His.InsertOnSubmit(smh);
                        context.SubmitChanges();
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Write("OrderService.AddStock:" + ex.Message);
                    return false;
                } 
            }
        }

        [OperationContract]
        public List<VW_StockMngHis> GetStockManageHis(DateTime Start,DateTime End, int DeviceID,string UserID,int PageIndex,int PageSize )
        {
            try
            {
                Authoricate();
                using (OrderDataClassesDataContext context = new OrderDataClassesDataContext())
                {
                    var query = from q in context.VW_StockMngHis
                                where (DeviceID==-1|| q.Device_ID == DeviceID) && (string.IsNullOrEmpty(UserID)|| q.User_ID==UserID)
                                where q.Create_Time>=Start
                                where q.Create_Time<=End
                                orderby q.Create_Time
                                select q;
                    if (query.Any())
                    {
                        int count = query.Count();
                        int start = (PageIndex - 1) * PageSize;
                        
                        if (start > count)
                        {
                            return new List<VW_StockMngHis>();
                        }
                        

                        return query.Skip(start).Take(count-start>PageSize?PageSize:count-start).ToList();

                    }
                    return new List<VW_StockMngHis>();
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("OrderService.GetStockManageHis:" + ex.Message);
                return null;
            }
        }

        [OperationContract]
        public List<VW_OrderHIS> GetOrderHis(string Serv_Number,DateTime Start,DateTime End )
        {

            try
            {
                Authoricate();
                using (OrderDataClassesDataContext context = new OrderDataClassesDataContext())
                {
                    var query = from q in context.VW_OrderHIS
                                where  (string.IsNullOrEmpty(Serv_Number) || q.Serv_Number == Serv_Number)
                                where q.Order_Time>=Start
                                where q.Order_Time<=End
                                orderby q.Order_Time
                                select q;
                    if (query.Any())
                    {
                        int count = query.Count();
                        return query.Take(count > 100 ? 100 : count).ToList();

                    }
                    return new List<VW_OrderHIS>();
                }
            }
            catch (Exception ex)
            {
                LogManager.Write("OrderService.GetOrderHis:" + ex.Message);
                return null;
            }
        }
        [OperationContract]
        public string ExportHisByFile(string Serv_Number, string Start, string End)
        {
            DataTable table= null;
            string cmdtext=string.Format("select ID 预约工单,Device_ID 终端ID,Device_Name 终端名称,"+
                        "Serv_Number 用户号码,Sts 状态,Order_Time 预约时间,UserName 受理工号,ChannelName 受理渠道,Remark 备注 "+
                        "from VW_OrderHIS where Sts=\'有效\' and order_time between \'{0} 00:00:00\' and \'{1} 23:59:59\'",
                        Start, End);
            try
            {
                using (SqlConnection con = new SqlConnection(SqlString))
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandTimeout = 600;
                    cmd.Connection = con;
                    cmd.CommandText = cmdtext;
                    if (!string.IsNullOrEmpty(Serv_Number))
                    {
                        cmd.CommandText += string.Format(" and serv_number=\'{0}\'", Serv_Number);
                    }

                    cmd.CommandText += " order by order_time";

                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    table = new System.Data.DataTable();
                    sda.Fill(table);
                }
            }
            catch (Exception ex1)
            {

                LogManager.Write("OrderService.ExportHisByFile 查询失败:" + ex1.Message + "--" + cmdtext);
                return "-1";
            }

            try
            {
                return this.WriteTableIntoFile(table, "终端预约记录");
            }
            catch (Exception ex2)
            {
                LogManager.Write("OrderService.ExportHisByFile 导出失败:" + ex2.Message);
                return "-1";
            }
        }
        

        [OperationContract]
        public bool CancelUserOrder(int OrderID,string Remark)
        {
            lock (this)
            {
                try
                {
                    Authoricate();
                    using (OrderDataClassesDataContext context = new OrderDataClassesDataContext())
                    {
                        var query = from q in context.Order_His
                                    where q.ID == OrderID
                                    where q.Is_Cancel=='0'
                                    select q;
                        if (query.Any())
                        {

                            query.First().Is_Cancel = '1';
                            query.First().Remark = Remark;

                            var stock = from c in context.Order_Stock
                                    where c.Device_ID == query.First().Device_ID
                                    select c;
                            if (stock.Any())
                            {
                                stock.First().Stock++;

                                 context.SubmitChanges();
                                 return true;
                            }
                            else
                            {
                                return false;
                            }

                           
                        }
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    LogManager.Write("OrderService.CancelUserOrder:" + ex.Message);
                    return false;
                } 
            }
        }

        [OperationContract]
        public XDataTable GetOrderReport(ReportType Report,
            string Start, string End, string AreaCode,string DistrictID,string ChannelID)
        {
            DataTable table = new DataTable("Report");
            try
            {
                using (SqlConnection con = new SqlConnection(this.SqlString))
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandTimeout = 300;
                    cmd.CommandType = CommandType.StoredProcedure;
                    if (Report == ReportType.ChannelOrder)
                    {
                        cmd.CommandText = "SP_ChannelOrder";
                    }
                    else if (Report == ReportType.IllgalOrder)
                    {
                        cmd.CommandText = "SP_ChannelIllgalOrder";
                    }
                    else
                    {
                        return null;
                    }
                    cmd.Parameters.AddRange(new SqlParameter[]
                {
                    new SqlParameter("@AreaCode",AreaCode),
                    new SqlParameter("@Start",Start),
                    new SqlParameter("@End",End),
                    new SqlParameter("@ChannelID",ChannelID),
                    new SqlParameter("@PQID",DistrictID)
                });

                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    sda.Fill(table);

                }
            }
            catch (Exception ex1)
            {

                LogManager.Write("OrderService.GetOrderReport执行过程失败：" + ex1.Message);
                return null;
            }

            try
            {
                return new XDataTable(table);
            }
            catch (Exception ex2)
            {
                
                LogManager.Write("OrderService.GetOrderReport转换失败：" + ex2.Message);
                return null;
            }
        }



        

    }

    public enum ReportType
    {
        ChannelOrder,
        IllgalOrder
    }
}
